package com.ruin.tech.ahri.service.impl;

import com.google.common.collect.Lists;
import com.ruin.tech.ahri.model.dto.CalculatorDTO;
import com.ruin.tech.ahri.service.ICalculator;
import com.ruin.tech.ahri.utils.Format;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: yuegc
 * @description:
 * @create: 2019/12/13 14:02
 */
@Slf4j
@Service
public class CalculatorImpl implements ICalculator {
    /**
     * 计算等额本息还款
     * @return
     */
    public List<String> equalInstallmentsOfPrincipalAndInterest(CalculatorDTO calculatorDTO) {
        List<String> data = Lists.newArrayList();
        double monthRate = calculatorDTO.getRate() / (100 * 12);//月利率
        double preLoan = (calculatorDTO.getPrincipal() * monthRate * Math.pow((1 + monthRate),
                calculatorDTO.getMonths())) / (Math.pow((1 + monthRate), calculatorDTO.getMonths()) - 1);//每月还款金额
        double totalMoney = preLoan * calculatorDTO.getMonths();//还款总额
        double interest = totalMoney - calculatorDTO.getPrincipal();//还款总利息
        data.add(Format.format(totalMoney));//还款总额
        data.add(Format.format(calculatorDTO.getPrincipal()));//贷款总额
        data.add(Format.format(interest));//还款总利息
        data.add(Format.format(preLoan));//每月还款金额
        data.add(String.valueOf(calculatorDTO.getMonths()));//还款期限
        return data;
    }

    /**
     * 计算等额本金还款
     * @return
     */
    public List<String> equivalentPrincipal(CalculatorDTO calculatorDTO) {
        List<String> data = Lists.newArrayList();
        double monthRate = calculatorDTO.getRate() / (100 * 12);//月利率
        double prePrincipal = calculatorDTO.getPrincipal() / calculatorDTO.getMonths();//每月还款本金
        double firstMonth = prePrincipal + calculatorDTO.getPrincipal() * monthRate;//第一个月还款金额
        double decreaseMonth = prePrincipal * monthRate;//每月利息递减
        double interest = (calculatorDTO.getMonths() + 1) * calculatorDTO.getPrincipal() * monthRate / 2;//还款总利息
        double totalMoney = calculatorDTO.getPrincipal() + interest;//还款总额
        data.add(Format.format(totalMoney));//还款总额
        data.add(Format.format(calculatorDTO.getPrincipal()));//贷款总额
        data.add(Format.format(interest));//还款总利息
        data.add(Format.format(firstMonth));//首月还款金额
        data.add(Format.format(decreaseMonth));//每月递减利息
        data.add(String.valueOf(calculatorDTO.getMonths()));//还款期限
        return data;
    }
}
